package com.insigma.business.qrcode.welfare.service.impl;

import com.google.common.collect.Maps;

import com.insigma.business.qrcode.soldier.entity.SoldierBasicInfoDO;
import com.insigma.business.qrcode.soldier.service.SoldierBasicInfoService;
import com.insigma.business.qrcode.soldier.util.SecurityUtil;
import com.insigma.business.qrcode.welfare.dto.MarketingSpotCommonInput;
import com.insigma.business.qrcode.welfare.service.MarketingSpotMaterialsTransform;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("jzdyfTransform")
public class MarketingSpotMaterialsTransformImpl implements MarketingSpotMaterialsTransform {

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    private String secretKey = "zjdyftyjr2020";

    @Override
    public String transform(MarketingSpotCommonInput input) {
        String materials = input.getMaterials();
        String soldierId = input.getSoldierId();
        if (StringUtils.isBlank(materials) || StringUtils.isBlank(soldierId)) {
            return null;
        }
        
        SoldierBasicInfoDO basicInfo = soldierBasicInfoService.getByQrSuccess(soldierId);
        if (basicInfo != null) {
            materials = materials.replace("${userId}", soldierId);
            materials = materials.replace("${userName}", basicInfo.getRealName());
            materials = materials.replace("${userPhone}", basicInfo.getMobile());
            materials = materials.replace("${sign}", generateSign(basicInfo));
            return materials;
        }
        return null;
    }

    private String generateSign(SoldierBasicInfoDO basicInfo) {
        Map<String, String> map = Maps.newHashMap();
        map.put("userId", basicInfo.getSoldierId());
        map.put("userName", basicInfo.getRealName());
        map.put("userPhone", basicInfo.getMobile());

        return SecurityUtil.signRequest(map, secretKey);
    }

}
